<?php
/**
 * 材料供应商（基础）模型
 * (model)
 */
namespace App\Models\Product;

use App\Models\Basics\SupplierM;
use Illuminate\Database\Eloquent\Relations\Pivot;

class ProductSupplierM extends Pivot
{
    protected $table = 'product_supplier_m';

    /**
     * 标识 ID 是否自增。
     * @var bool
     */
    public $incrementing = true;

    public $timestamps = false;

    protected $guarded = [];

    //功能性
    public static $_function = [
        1  => '抗紫外线50+',
        2  => '抗菌功能',
        3  => '凉感功能',
        4  => '吸湿速干',
        5  => '环保再生',
        6  => '液氨整理',
        7  => '消臭功能',
        8  => '智能温控',
        9  => 'SORONA',
        10  => 'COUDURA',
    ];
    //报价单位
    public static $_quote_currency = [
        1  => '元/码',
        2  => '元/米',
        3  => '元/个',
        4  => '元/件',
        5  => '元/公斤',
        6  => '元/条',
    ];
    //后整理
    public static $_test_after = [
        1  => '涂层',
        2  => '贴合',
        3  => '泼水',
        4  => '压光',
        5  => '压花',
        6  => '印花',
        7  => '普通整理',
        8  => '功能整理',
        9  => '无',
    ];
    //成分
    public static $_composition = [
        1  => '聚酯纤维',
        2  => '锦纶',
        3  => '氨纶',
        4  => '棉',
        5  => '亚麻',
        6  => '桑蚕丝',
        7  => '绵羊毛',
        8  => '莫代尔',
        9  => '莱赛尔',
        10  => '天丝',
    ];
    //门幅单位
    public static $_door_unit = [
        1  => 'INCH',
        2  => 'CM',
    ];

    //是否默认
    public static $_status = [
        0 => '否',
        1 => '是',
    ];

    const AUDIT_NO = 1;      //未审核
    const AUDIT_SUCCESS = 2; //审核通过
    const AUDIT_REJECT = 3;  //审核拒绝
    public static $_auditStatus = [
        self::AUDIT_NO      => '未审核',
        self::AUDIT_SUCCESS => '已通过',
        self::AUDIT_REJECT  => '已拒绝',
    ];

    protected $casts = [
        'function' => 'array',//功能性
        //'composition' => 'json',//成分
    ];
    //public function getCompositionAttribute($value)
    //{
    //    return array_values(json_decode($value, true) ?: []);
    //}
    //
    //public function setCompositionAttribute($value)
    //{
    //    $this->attributes['composition'] = json_encode(array_values($value));
    //}

    public function supplier(){
        return $this->belongsTo(SupplierM::class,'supplier_id');
    }

    public function material(){
        return $this->belongsTo(ProductMaterial::class,'material_id','id');
    }

    protected static function boot()
    {
        parent::boot();

        static::deleting(function ($model){
            if($model->audit_status == 2){
                throw new \Exception('材料说明书已审核请勿删除');
            }
        });
    }

    public static function modifyDefaultPuSupplier($id,$materialId){
        return self::query()
            ->where('id','<>',$id)
            ->where('material_id',$materialId)
            ->update(['status' => 0]);
    }

    /**
     * 采购计划确认时需按指定SKU去选择采购供应商
     * 获取关联产品的所有供应商
     * @param $materialId
     * @return \Illuminate\Database\Eloquent\Builder[]|\Illuminate\Database\Eloquent\Collection|\Illuminate\Support\Collection
     */
    public static function getSupplierOptionByMaterial($materialId){
        return self::query()
            ->with('supplier')
            ->where('material_id',$materialId)
            ->get()
            ->map(function ($item){
                return collect(['supplier_id' => $item->supplier->id ?? '','supplier_name' => $item->supplier->name ?? '']);
            })
            ->pluck('supplier_name','supplier_id');
    }

    const FILE_NAME_DIR = 'material';

    const FILE_DIR = 'app'.DIRECTORY_SEPARATOR.self::FILE_NAME_DIR;

    public static function getFile($supplierMShortName,$materialCode){
        $fileDir = self::fileDir();
        $fileName = self::fileName($supplierMShortName,$materialCode);
        $filePath = storage_path($fileDir).DIRECTORY_SEPARATOR.$fileName;
        $fileDir = dirname($filePath);
        if(!is_dir($fileDir)){
            mkdir($fileDir,0777,true);
            chmod($fileDir, 0777);
        }
        return $filePath;
    }

    public static function fileDir(){
        return self::FILE_DIR;
    }

    public static function fileName($supplierMShortName,$materialCode){
        return $supplierMShortName.'_'.$materialCode.'-ProductMaterialFile.pdf';
    }

    /**
     * 供应商搜索选项
     * @return \Illuminate\Database\Eloquent\Builder[]|\Illuminate\Database\Eloquent\Collection|\Illuminate\Support\Collection
     */
    public static function supplierMOptions(){
        $supplierId = self::query()->groupBy('supplier_id')->pluck('supplier_id');
        $query = SupplierM::query()->whereIn('id',$supplierId);
        $res = $query->get()->map(function ($model){
            return collect(['name' => $model->short_name.'-'.$model->name,
                'id' => $model->id]);
        });
        return $res->pluck('name','id');
    }

    /**
     * 材料搜索选项
     * @return \Illuminate\Database\Eloquent\Builder[]|\Illuminate\Database\Eloquent\Collection|\Illuminate\Support\Collection
     */
    public static function materialOptions(){
        $materialId = self::query()->groupBy('material_id')->pluck('material_id');
        $query = ProductMaterial::query()->whereIn('id',$materialId);
        $res = $query->get()->map(function ($model){
            return collect(['material' => $model->material_code.'-'.$model->title,
                'id' => $model->id]);
        });
        return $res->pluck('material','id');
    }
}
